<?php
class Voucher extends CS_Controller
{
    function _init()
    {
		$this->load->library('pagination');
        $this->load->model('user_model', 'user');
		$this->load->model('user_type_model', 'user_type');
		$this->load->model('user_account_model', 'user_account');
		$this->load->model('user_detail_model', 'user_detail');
		$this->load->model('voucher_model', 'voucher');
    }
	
	public function grid($pg=1)
	{
		$getData = $this->input->get();
		if (isset($getData['excel']) && $getData['excel']== 'excel') {
            $this->excelExport($getData);
        } else {
			$page_num = 20;
            $num = ($pg-1)*$page_num;
            $config['first_url']   = base_url('voucher/grid').$this->pageGetParam($this->input->get());
            $config['suffix']      = $this->pageGetParam($this->input->get());
            $config['base_url']    = base_url('voucher/grid');
            $config['total_rows']  = $this->voucher->total($this->input->get());
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_list']   = $this->pagination->create_links();
            $data['page_list'] = $this->voucher->page_list($page_num, $num, $this->input->get());
            $data['all_rows']  = $config['total_rows'];
            $data['pg_now']    = $pg;
		    $data['voucher_type'] = array(1=>'可提现', 2=>'游币'); //充值类型
		    $data['voucher_status'] = array(1=>'未派发', 2=>'已派发'); //派发状态
			$data['user_type'] = $this->user_type->find()->result_array();
			foreach ($data['user_type'] as $key=>$value)
			{
				if((1==$value['type_id'])||(2==$value['type_id'])||(65536==$value['type_id'])||(131072==$value['type_id']))//去掉供应商，二级供应商，检票人员，终端设备
				{
					unset($data['user_type'][$key]);
				}
			}
			$data['get_way'] = array(1=>'创建账号', 2=>'充值'); //获取代金券方式
		    $this->load->view('voucher/grid', $data);
		}
	}
	
	public function excelExport($getData)
    {
        $result = $this->voucher->excelExport($getData);
        if($result->num_rows() <= 0){
            $this->error('voucher/grid', null, '这个时间段没有记录');
        }
        if($result->num_rows() > 10000){
            $this->error('voucher/grid', null, '由于导出的数据太多，请选择一个时间范围');
        }
        $arrayOrder = $result->result_array();

        array_unshift($arrayOrder, array('ID','串码','类型（1可提现2游币）','金额','状态（1未派发2已派发）','溢价值','用户名','创建时间'));
        $this->load->library('excel');
        $this->excel->addArray($arrayOrder);
        $this->excel->generateXML(date('Ymd').'voucher');
    }
	
    public function addPost()
    {
		$vou_count = $this->input->post('count');//代金券数量
		$type = $this->input->post('type');//充值类型
		$amount = $this->input->post('amount');//代金券金额
		$parent_user = $this->input->post('parent_user');//父级账号
		$letters = $this->input->post('letters');//账号前缀
		$digi_count = $this->input->post('digi_count');//账号后缀数字个数
		$over_beizhu = $this->input->post('over_beizhu');//溢价值
		$userType = $this->input->post('userType');
		
		if($vou_count<=0)
		{
			$this->error('voucher/grid', '', '代金券数量必须大于零！');
		}
		if($amount<=0)
		{
			$this->error('voucher/grid', '', '代金券金额必须大于零！');
		}
		if((strlen($letters) + $digi_count) > 31)
		{
			$this->error('voucher/grid', '', '首字母个数加上数字个数不能超过31！');
		}
		if((2==$type) && (intval($amount) != $amount))
		{
			$this->error('voucher/grid', '', '游币金额请输入整数！');
		}
		if ($this->validateParam($userType)) 
		{
			$this->error('voucher/grid', '', '请选择账户类型！');
		}
		
		$parent_user = $parent_user?$parent_user:'bz_teck';
		$letters = $letters?$letters:'djq2';
		$digi_count = $digi_count?$digi_count:6;
		$over_beizhu = $over_beizhu?$over_beizhu:75.00;
		
		//获取用户类型值
		$opt = 0;
        foreach ($userType as $value){
            $opt += $value;
        }
        $user_type = ($opt!=0)?$opt:528384;//默认分销商|交易者（4096|524288）
		
		//生成最大数字，判断能生成的代金券个数是否足够
		$max = 0;
		for($i=1;$i<=$digi_count;$i++)
		{
			$max = $max*10+9;
		}
		if($max + 1 < $vou_count)
		{
			$this->error('voucher/grid', '', '数字个数不足，无法生成足够多的代金券');
		}
		
		//获取父级账户ID
		$res_parent = $this->user->validateName($parent_user);
		if($res_parent->num_rows()<=0)
		{
			$this->error('voucher/grid', '', '父级账号不存在！');
		}
		$parent_id = $res_parent->row()->uid;
		
		$succ_count = 0;
		//生成并保存代金券
		for($i=0;$i<$vou_count;$i++)
		{
			$code = $this->getRandChar(12);
			
			$data_voucher = array(
			     'code'        => $code,
				 'type'        => $type,
				 'amount'      => $amount,
				 'status'      => 1,//未派发
				 'prefix'      => $letters,
				 'digi_count'  => $digi_count,
				 'parent_id'   => $parent_id,
				 'over_beizhu' => $over_beizhu,
				 'user_type'   => $user_type,
				 'created_at'  => date("Y-m-d H:i:s",time()),
		    );
			$res = $this->voucher->insert($data_voucher);
            if ($res)
			{
				$succ_count++;
			}
		}
		
        if($succ_count>0)
            $this->success('voucher/grid', '', '共生成了'.$succ_count.'张代金券。');
		else
		    $this->error('voucher/grid', '', '生成代金券失败。');
    }
	
	private function getRandChar($length)
	{
        $str = '';
        $strPol = "23456789abcdefghijkmnpqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[mt_rand(0,$max)];//mt_rand($min,$max)生成介于min和max两个数之间的一个随机整数    
	    }

        return $str;
    }
}
